#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdarg>

#include <deque>
#include <sstream>
using namespace std;

#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <glib.h>

#include "control.h"
#include "errors.h"
#include "colour.h"
#include "sound.h"
#include "screen.h"
#include "global.h"
#include "img.h"

GMainLoop* loop = NULL;

static FILE* elog = NULL;

void log_print(const char* file, const unsigned long line, const char* format, ...) {
	va_list args;
	static char buffer[1024];

	va_start(args, format);
	vsprintf(buffer, format, args);

	fprintf(elog, "%s:%ld : %s\n", file, line, buffer);
	fprintf(stderr, "%s:%ld : %s\n", file, line, buffer);

	fflush(elog);
	fflush(stderr);
}

void kill(void) {
	kill_sound();
	kill_control();
	kill_img();
	kill_screen();
	if (elog) {
		fclose(elog);
	}
#ifdef GP2X
	chdir("/usr/gp2x");
	execl("/usr/gp2x/gp2xmenu", "/usr/gp2x/gp2xmenu", NULL);
#endif
}

static int init(int* argc, char** argv) {
	int done;
	elog = fopen(ELOG_FILE, "w");
	
	if ((done = init_img()))
		return done;
	if ((done = init_sound(argc, argv)))
		return done;
	if ((done = init_screen()))
		return done;
	if ((done = init_control()))
		return done;
	return 0;
}

int main (int argc, char* argv[])
{
	int done;
	atexit(kill);
  if ((done = init(&argc, argv)))
		exit(done);

	set_bg("images/bwiiuup_mentok.jpg");
	loop = g_main_loop_new(NULL, FALSE);

	//load_tracks("music");

	g_idle_add(idle_screen, NULL);
	g_idle_add(idle_control, NULL);
	g_main_loop_run(loop);

	return EXIT_OK;
}

/* vim:set ts=2 sts=2 sw=2 noexpandtab: */
